<template>
	<div class="zh-add-manual">
		<nav-header>
			<template slot="menuBefore">
				<li><router-link to="/portal/help/operation-manual" tag="a">操作手册管理</router-link></li>
				<li class="gap">&gt;</li>
			</template>
		</nav-header>
		<div class="zh-upload">
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
				<el-form-item label="手册标题" prop="title" style="width: 450px">
				    <el-input v-model="ruleForm.title" placeholder="20个字符内" maxLength="20" clearable></el-input>
				</el-form-item>
				<el-form-item label="文件上传" prop="select_or_not">
				     <uploader :options="uploadOptions" :autoStart="false" ref="uploader" :file-status-text="statusText" @files-submitted="fileSubmit"  @file-removed="fileRemoved" @file-success="fileSuccess" @file-error="fileFail"  class="uploader-example">
					    <uploader-unsupport></uploader-unsupport>
					    <uploader-btn :directory="false" :attrs="attrs" v-if="selectFileShow" :single="true">选择文件（仅支持doc、docx的文件）</uploader-btn>
					    <uploader-list  v-if="selectFileShow===false?true:false"></uploader-list>
					 </uploader>
				</el-form-item>
				<el-form-item>
					<el-button size="medium" @click="goBack">取消</el-button>
					<el-button size="medium" type="primary" @click="submitForm('ruleForm')">确定</el-button>
				</el-form-item>
			</el-form>
		</div>
	</div>
</template>
<script>
    import {uploaderFileFail} from './../../../tools/tool';

	export default {
	    data() {
		    return {
		    	statusText: {
			      	success: '上传成功',  
			      	error: '上传出错',  
			     	uploading: '正在上传...',  
			      	paused: '暂停',  
			      	waiting: '等待上传'  
				},
				selectFileOrNot:false,  //是否选中文件
			    uploadOrNot:false, 		//是否已经上传
			    uploadInfo:{
					file_name:'',
					file_path:'',
					file_size:0
				},
				attrs: {
			      	accept: ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/msword']
			    },
		    	uploadOptions: {
			          target: this.BASE_URL+'/api/resource/res_upload',
			          testChunks: false,
			          headers:{Authorization : `Bearer `+this.$g.access_token},
			    },
		        ruleForm: {
	                title: '',
	                select_or_not:'',
	            },
	            rules: {
	              	title: [
						{ pattern: /^\S+$/, message:'不能包含空格'},
		                { required: true, validator: this.validateName, message: '20个字符内', trigger: 'blur' },
		                { min: 3 ,max:20 , message: '标题长度在3-20个字符内' , trigger: 'blur' },
	            	],
	            	 select_or_not: [
		            	{ required: true, validator: this.validateName, message: '请选择文件' }
		            ],
	      		},
	      		selectFileShow:true,//是否显示选择文件按钮
				uploadRetryTimes:100,//文件最大重传次数
	      	}
	    },
	    methods: {
			goBack() {
				this.$router.push('/portal/help/operation-manual');
			},
	    	//验证
			validateName(rule, value, callback){
				if ( is_empty( value ) ) {
					return callback(new Error('请输入手册标题'));
				} else {
					callback()
				}
			},
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						if( this.selectFileOrNot ){
							this.fileUpload();
						}else{
							this.resourceSave();
						}
					} else {
						return false;
					}
				});
			},
	        resourceSave(){
				let resourceParam = deep_clone( this.ruleForm );
				if( this.uploadOrNot ) {
					resourceParam.file_name = this.uploadInfo.file_name;
					resourceParam.path = this.uploadInfo.file_path;
					resourceParam.size = this.uploadInfo.file_size;
					resourceParam.postfix = this.uploadInfo.post_fix;
				}
            	let success = ( data=>{
            		this.$message.success(data.msg);
            		this.$router.push('/portal/help/operation-manual');
            	})
            	let fail = ( data =>{
            		this.$message.error(data.msg)
            		this.$refs.uploader.uploader.cancel();
            	})
            	//执行请求，并将回调方法变成config成员以便鉴权过期可以执行
            	if( !is_empty( resourceParam.id ) && parseInt( resourceParam.id ) > 0 ){
            		this.$ajax.put('api/setting/operation_manual',resourceParam,{func:{success:success,fail:fail}})
            	}else{
					this.$ajax.post('api/setting/operation_manual',resourceParam,{func:{success:success,fail:fail}})	
            	}
            	
            	
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
			},
			//上传成功的事件  
			fileSuccess (rootFile, file, message, chunk) { 
                var mess = eval('(' + message + ')');
                mess = handleResponseData( mess );
                
			 	if(parseInt( mess.data.status ) ===1 ){
			  		this.uploadOrNot = true;
			  		this.uploadInfo.file_name = mess.data.file_name;
			  		this.uploadInfo.file_path = mess.data.file_path;
			  		this.uploadInfo.post_fix = mess.data.post_fix;
			  		this.resourceSave();
			  }
			},
			fileFail(rootFile, file, message, chunk) {
                uploaderFileFail(this, Uploader, file, message);
			},
			//过滤文件格式
			fileSubmit(files, fileList, event){
				for (var i = 0 ; i < fileList.length ; i++ ) {
					if(!this.attrs.accept.includes(fileList[i].fileType)){
						this.$message.warning('只允许上传doc、docx格式的文件')
						this.$refs.uploader.uploader.removeFile( fileList[i] );
					}else{
						if( this.$refs.uploader.uploader.fileList.length  > 1  ){
							//删除第一张图片
							this.$refs.uploader.uploader.removeFile( this.$refs.uploader.uploader.fileList[0] );
						}
						this.ruleForm.select_or_not = '1';
						this.uploadInfo.file_size = fileList[i].size;
						this.selectFileOrNot = true;
						this.selectFileShow = false;
						
						// 清空验证信息
						this.$refs['ruleForm'].validateField('select_or_not');
					}
				}
			},
			fileRemoved(file){
				this.ruleForm.select_or_not = '';
				this.selectFileOrNot = false;
				this.selectFileShow = true;
			},
			fileUpload(){
				Uploader.upload();
			},
	    },
	    mounted () { 
			// 获取uploader对象  
			this.$nextTick(() => {  
				window.Uploader = this.$refs.uploader.uploader  
			})  
		}  
	}
</script>
<style lang="scss">
	.zh-add-manual {
		.zh-upload {
			margin-top: 20px;
			.submit-button {
				text-align: left;
				margin-left: 100px;
			}
		}
		.uploader-list {
		    .uploader-file-pause {
		      display: none !important;
		    }
		    .uploader-file-status {
		      text-indent: 0;
		    }
 		 }
	}

</style>